package com.lagou.study.filter;

import com.lagou.study.service.UserFeignClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenFilter implements GlobalFilter, Ordered {
    public final static String ATTRIBUTE_IGNORE_TOKEN_GLOBAL_FILTER = "@ignoreTokenGlobalFilter";

    @Autowired
    UserFeignClientService userFeignClientService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //跳过检测
        if (exchange.getAttribute(ATTRIBUTE_IGNORE_TOKEN_GLOBAL_FILTER) != null) {
            return chain.filter(exchange);
        }else {
            ServerHttpResponse response = exchange.getResponse();
            MultiValueMap<String, HttpCookie> cookies = exchange.getRequest().getCookies();
            HttpCookie cookie = cookies.getFirst("token");
            if (cookie == null) {
                return chain.filter(exchange);
            } else {
                String token = cookie.getValue();
                String email = userFeignClientService.info(token);
                if ("".equals(email)) {
                    response.setStatusCode(HttpStatus.SEE_OTHER);
                    response.getHeaders().set(HttpHeaders.LOCATION, "http://www.test.com/static/login.html");
                    return response.setComplete();
                } else {
                    /*String url = "http://www.test.com/static/welcome.html";
                    response.setStatusCode(HttpStatus.SEE_OTHER);
                    response.getHeaders().set(HttpHeaders.LOCATION, url);
                    return response.setComplete();*/
                    return chain.filter(exchange);
                }
            }
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
